import React, { useEffect, useState } from 'react'
import { useStore } from 'react-redux'
import { FileDoneOutlined, UploadOutlined } from '@ant-design/icons'
import http from '../../api'
import { Space, Table, Button, message } from 'antd'
import { useHistory } from 'react-router-dom'

export default function Audit() {
    const [auditList, setAuditList] = useState([])//草稿列表
    const [newsClassify, setNewsClassify] = useState([])
    const { UserInfo } = useStore().getState()
    const history = useHistory()

    //编辑打开详情
    const viewDraft = (record) => {
        //嵌套子路由跳转不使用绝对路径
        history.push(`/news-manage/preview/${record.id}`, record)
    }

    // 提交审核 审核通过设置为已通过 待发布 审核不通过设置为未通过 未发布
    // const auditList = ['未审核', '审核中', '已通过', '未通过']
    // const publishList = ['未发布', '待发布', '已上线', '已下线']
    const handelAudit = (item, auditState, publishState) => {
        http.patch(`/news/${item.id}`, {
            auditState: auditState,
            publishState: publishState
        }).then(res => {
            getTableList()
            message.info('操作成功')
        })
    }

    const column = [
        {
            title: 'ID',
            key: 'id',
            dataIndex: 'id',
        },
        {
            title: '新闻标题',
            key: 'title',
            render: (_, item) => (
                <span style={{ color: "#1890ff" }} onClick={() => viewDraft(item)}>{item.title}</span>
            )
        },
        {
            title: '作者',
            dataIndex: 'author',
            key: 'author',
        },
        {
            title: '新闻分类',
            key: 'categoryId',
            render: (_, item) => (
                <span>{newsClassify.length > 0 ? newsClassify.find(classItem => classItem.id == item.categoryId).title : ''}</span>
            )
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Button icon={<FileDoneOutlined />} onClick={() => handelAudit(record, 2, 1)} >通过</Button>
                    &nbsp;&nbsp;
                    <Button danger icon={<UploadOutlined />} onClick={() => handelAudit(record, 3, 0)} >驳回</Button>
                </Space>
            ),
        },
    ]

    useEffect(() => {
        getTableList()
        getNewsClassify()
    }, [])


    //获取新闻列表
    const getTableList = () => {
        http.get(`/news?author=${UserInfo.username}&auditState=0`).then(res => {
            setAuditList(res.data)
        })
    }

    //获取新闻分类信息
    const getNewsClassify = () => {
        http.get('/categories').then(res => {
            setNewsClassify(res.data)
        })
    }

    return (
        <div>
            <h1>审核新闻</h1>
            <Table columns={column} dataSource={auditList} pagination={{ pageSize: 5 }} rowKey={(item) => item.id} />;
        </div>
    )
}
